package com.bindapp.model;


import android.content.Context;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bindapp.R;
import com.bindapp.databinding.ActivityDevicewdBinding;
import com.bindapp.widget.MarkView;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by apple on 2018/7/2.
 */

public class ControllerSWModel extends BaseModel {
    private ActivityDevicewdBinding binding;
    private Map<Integer, String> xMap = new HashMap<>();
    private List<Entry> yVals1;
    private TimePickerView timePickerView;
    private List<TextView> xqlist = new ArrayList<TextView>();

    public ControllerSWModel(Context context) {
        super(context);
        binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.activity_devicewd, null, false);
        binding.setClick(new ViewClick());
        initChart();
        initTime();
        binding.linechart.setHighlightPerDragEnabled(true);
        binding.linechart.highlightValue(0, 0, true);
        xqlist.add(binding.one);
        xqlist.add(binding.two);
        xqlist.add(binding.three);
        xqlist.add(binding.four);
        xqlist.add(binding.five);
        xqlist.add(binding.six);
        xqlist.add(binding.seven);
    }

    private void initTime() {
        timePickerView = new TimePickerBuilder(context, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                Log.e("Mytext", "" + date.getTime());
            }
        }).setType(new boolean[]{false, true, true, true, true, false})
                .setCancelText("取消")
                .setSubmitText("确定")
                .setOutSideCancelable(false)
                .setTitleText("请选择时间")
                .isCyclic(true)
                .isDialog(false)
                .build();
    }

    public class ViewClick {
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.one:
                    changeXq((TextView) view);
                    break;
                case R.id.two:
                    changeXq((TextView) view);
                    break;
                case R.id.three:
                    changeXq((TextView) view);
                    break;
                case R.id.four:
                    changeXq((TextView) view);
                    break;
                case R.id.five:
                    changeXq((TextView) view);
                    break;
                case R.id.six:
                    changeXq((TextView) view);
                    break;
                case R.id.seven:
                    changeXq((TextView) view);
                    break;
                case R.id.spanner1:
                    new TimePickerBuilder(context, new OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            Log.e("Mytext", date.getHours() + "----" + date.getMinutes());
                            binding.spanner1.setText(date.getHours()+":"+date.getMinutes());
                            binding.spanner1.setGravity(Gravity.CENTER);
                        }
                    })
                            .setType(new boolean[]{false, false, false, true, true, false})
                            .setCancelText("取消")
                            .setSubmitText("确定")
                            .setOutSideCancelable(false)
                            .setTitleText("请选择时间")
                            .isCyclic(true)
                            .isDialog(false)
                            .build().show();
                    break;
                case R.id.spanner2:
                    new TimePickerBuilder(context, new OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            Log.e("Mytext", date.getHours() + "----" + date.getMinutes());
                            binding.spanner2.setGravity(Gravity.CENTER);
                            binding.spanner2.setText(date.getHours()+":"+date.getMinutes());
                        }
                    })
                            .setType(new boolean[]{false, false, false, true, true, false})
                            .setCancelText("取消")
                            .setSubmitText("确定")
                            .setOutSideCancelable(false)
                            .setTitleText("请选择时间")
                            .isCyclic(true)
                            .isDialog(false)
                            .build().show();
                    break;
            }

        }
    }

    private void changeXq(TextView textView) {
        for (TextView view : xqlist) {
            view.setTextColor(ContextCompat.getColor(context, R.color.textcolor));
            view.setBackground(ContextCompat.getDrawable(context, R.drawable.day_bg));
        }

        textView.setTextColor(ContextCompat.getColor(context, R.color.seelbar));
        textView.setBackground(ContextCompat.getDrawable(context, R.drawable.stroke_blue));
    }

    public void initChart() {
        binding.linechart.setDrawBorders(false);
        binding.linechart.setBorderColor(ContextCompat.getColor(context, R.color.seelbar));
        binding.linechart.setBorderWidth(2);
        binding.linechart.setTouchEnabled(true);
        binding.linechart.setDragDecelerationFrictionCoef(0.9f);
        binding.linechart.setDragEnabled(true);
        binding.linechart.setScaleEnabled(true);
        binding.linechart.setDoubleTapToZoomEnabled(false);
        binding.linechart.setDrawGridBackground(false);
        binding.linechart.setHighlightPerDragEnabled(true);

        binding.linechart.setBackgroundColor(ContextCompat.getColor(context, R.color.white));
        binding.linechart.animateY(800);
        Description description = new Description();
        description.setText("");
        //设置描述信息
        binding.linechart.setDescription(description);
        binding.linechart.setMarker(new MarkView());
        //设置没有数据时显示的文本
        binding.linechart.setNoDataText("没有数据撒...");
        Legend l = binding.linechart.getLegend();
        //表头代表线条说明前的图形 可以设置线形,圆形,方形
        l.setForm(Legend.LegendForm.CIRCLE);
        //l.setTypeface(mTfLight);
        //表头字体大小
        l.setTextSize(11f);
        //表头线条说明的颜色
        //l.setTextColor(ContextCompat.getColor(context,R.color.black));
        //表头线条放置的位置
        //l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        //表头多条线条的排列方式
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //表头的说明是否绘制到图表内部
        l.setDrawInside(false);

        XAxis xAxis = binding.linechart.getXAxis();
        //xAxis.setTypeface(mTfLight);
        xAxis.setTextSize(8f);
        //X轴显示的位置
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //X轴
        //xAxis.setSpaceMin(0.5f);
        //X轴数据的颜色
        xAxis.setTextColor(ContextCompat.getColor(context, R.color.black_light));
        //是否绘制X轴的网格线
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(true);
        xAxis.setAxisLineWidth(1);
        xAxis.setAxisLineColor(ContextCompat.getColor(context, R.color.black_light));
        //TODO 设置x轴坐标显示的数量  加true才能显示设置的数量 一旦加true后续的x轴数据显示有问题,
        // xAxis.setLabelCount(5,true);
        final String[] valueArry = {"6:00", "7:00", "8:00", "9:00", "10:00", "11:00", "12:00"};
        xAxis.setLabelCount(valueArry.length, true);
        //设置竖线为虚线样子
        xAxis.enableGridDashedLine(10f, 10f, 0f);

        //图表第一个和最后一个label数据不超出左边和右边的Y轴
        // xAxis.setAvoidFirstLastClipping(true);
        setData(7, 30);

        /********************************************************************************/
        //final Map<Integer, String> xMap = new HashMap<>();
        for (int i = 0; i < yVals1.size(); i++) {
            xMap.put((int) yVals1.get(i).getX(), valueArry[i]);
        }
        //自定义x轴标签数据
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return xMap.get((int) value);
            }
        });


        //设置限制线 70代表某个该轴某个值，也就是要画到该轴某个值上
        LimitLine limitLine = new LimitLine(70);
        //设置限制线的宽
        limitLine.setLineWidth(1f);
        //设置限制线的颜色
        limitLine.setLineColor(Color.RED);
        //设置基线的位置
        limitLine.setLabelPosition(LimitLine.LimitLabelPosition.LEFT_TOP);
        limitLine.setLabel("我是基线，也可以叫我水位线");
        //设置限制线为虚线
        limitLine.enableDashedLine(10f, 10f, 0f);


        YAxis leftAxis = binding.linechart.getAxisLeft();
        leftAxis.setDrawAxisLine(false);
        //leftAxis.setTypeface(mTfLight);
        //Y轴数据的字体颜色
        leftAxis.setTextColor(Color.WHITE);
        leftAxis.setAxisLineColor(Color.WHITE);
        //左侧Y轴最大值
        leftAxis.setAxisMaximum(50f);
        //左侧Y轴最小值
        leftAxis.setAxisMinimum(0f);
        //是否绘制Y轴网格线
        leftAxis.setDrawGridLines(false);
        //TODO 什么属性?
        leftAxis.setGranularityEnabled(true);
        //左边Y轴添加限制线
        //leftAxis.addLimitLine(limitLine);
        //右侧Y轴坐标
        YAxis rightAxis = binding.linechart.getAxisRight();
        rightAxis.setEnabled(false);
        //rightAxis.setTypeface(mTfLight);
        rightAxis.setTextColor(Color.WHITE);
        rightAxis.setAxisMaximum(900);
        rightAxis.setAxisMinimum(0);
        rightAxis.setDrawGridLines(false);
        //是否绘制等0线
        rightAxis.setDrawZeroLine(true);
        rightAxis.setGranularityEnabled(false);
        binding.linechart.getLegend().setEnabled(false);
    }


    private void setData(int count, float range) {
        yVals1 = new ArrayList<>();

        for (int i = 0; i < count; i++) {
            float mult = range / 2f;
            float val = (float) (Math.random() * mult) + 20;
            BigDecimal b = new BigDecimal(val);
            yVals1.add(new Entry(i, b.setScale(1, BigDecimal.ROUND_HALF_UP).floatValue()));
        }

        //binding.wdvalue.setText(((int)yVals1.get(0).getY())+"°C");

        LineDataSet set1;

        if (binding.linechart.getData() != null &&
                binding.linechart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) binding.linechart.getData().getDataSetByIndex(0);
            set1.setValues(yVals1);
            set1.setCubicIntensity(20f);
            binding.linechart.getData().notifyDataChanged();
            binding.linechart.notifyDataSetChanged();

        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(yVals1, "数据1");

            set1.setHighlightEnabled(true);
            set1.setDrawHighlightIndicators(false);
            set1.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
            set1.setCubicIntensity(20.0f);
            //数据对应的是左边还是右边的Y值
            set1.setAxisDependency(YAxis.AxisDependency.LEFT);
            //线条的颜色
            set1.setColor(ContextCompat.getColor(context, R.color.seelbar));
            //表中数据圆点的颜色
            set1.setCircleColor(ContextCompat.getColor(context, R.color.seelbar));
            //表中数据线条的宽度
            set1.setLineWidth(2f);
            //表中数据圆点的半径
            set1.setCircleRadius(3f);
            //设置线面部分是否填充
            set1.setDrawFilled(false);
            //填充的颜色透明度
            set1.setFillAlpha(255);
            //填充颜色
            set1.setFillColor(ColorTemplate.rgb("ffffff"));
            set1.setHighLightColor(Color.rgb(244, 117, 117));
            //绘制的数据的圆点是否是实心还是空心
            set1.setDrawCircleHole(true);
            set1.setDrawValues(false);

//            LineData lineData = new LineData(xVals, set1);
            // create a data object with the datasets
            LineData data = new LineData(set1);
            //设置图标中显示数字的颜色
            data.setValueTextColor(ContextCompat.getColor(context, R.color.black_light));
            //设置图标中显示数字的大小
            data.setValueTextSize(9f);

            // set data
            binding.linechart.setData(data);
        }
    }


    class ChatSelectImpl implements OnChartValueSelectedListener {

        @Override
        public void onValueSelected(Entry e, Highlight h) {

        }

        @Override
        public void onNothingSelected() {

        }
    }

    @Override
    public ActivityDevicewdBinding getBinding() {
        return binding;
    }


}
